package com.sixmac.service.impl;

import com.sixmac.core.base.service.BaseService;
import com.sixmac.core.plugins.dao.Md;
import com.sixmac.core.toolbox.CMap;
import com.sixmac.core.toolbox.support.Convert;
import com.sixmac.model.CourseChapter;
import com.sixmac.service.CourseChapterService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * CourseChapterServiceImpl
 * 2018-07-03 17:19:48
 *
 * @author Blade
 */
@Service
public class CourseChapterServiceImpl extends BaseService<CourseChapter> implements CourseChapterService {


    public Integer getCourseIdByChapterCourseId(Integer courseId) {
        CourseChapter courseChapter = this.findById(courseId);
        if (courseChapter.getPid() == 0) {
            return courseChapter.getId();
        }
        return this.getCourseIdByChapterCourseId(courseChapter.getPid());
    }


    public Integer getPid(Integer courseId) {
        return this.getCourseIdByChapterCourseId(courseId);
    }

    @Override
    public boolean updateStatus(String ids, Integer status) {
        CMap map = CMap.init().set("status", status).set("ids", Convert.toIntArray(ids));
        boolean temp = updateBy("status = #{status}", "id in (#{join(ids)})", map);
        return temp;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Map<String, Object> findOne(Object id) {
        return Md.selectOne("courseChapter.findOne", CMap.init().set("id", id), Map.class);
    }


    public Integer deleteId(String ids) {
        String id[] = ids.split(",");
        for (String i : id) {
            this.deleteId(Convert.toInt(i));
        }
        Integer i = deleteByIds(ids);
        return i;
    }

    public void deleteId(Integer id) {
        List<CourseChapter> lists = new ArrayList<>();
        this.deleteByModel(id, lists);
        StringBuilder sb = new StringBuilder();
        for (CourseChapter c : lists) {
            sb.append(c.getId());
            sb.append(",");
        }
        if (!lists.isEmpty()) {
            deleteByIds(sb.substring(0, sb.length() - 1));
        }
    }

    public void deleteByModel(Integer id, List<CourseChapter> lists) {
        List<CourseChapter> courseChapterList = findBy("pid = #{id}", CMap.init().put("id", id));
        for (CourseChapter c : courseChapterList) {
            this.deleteByModel(c.getId(), lists);
            lists.add(c);
        }

    }


}
